package com.sy.shiro;


import com.google.gson.Gson;
import com.sy.common.persistence.BaseDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by alvawen on 2017/11/2 0002.
 */
@Slf4j
public class MyRestAuthFilter extends FormAuthenticationFilter {
    @Resource
    protected BaseDao baseDao;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//        httpServletResponse.setStatus(httpServletResponse.SC_UNAUTHORIZED);
//        try {
//            response.setContentType("application/json;charset=UTF-8");
//            httpServletResponse.getWriter().println(new Gson().toJson(MyRestResult.failureDefault("您还没有登录")));
//        } catch (Exception e1) {
//        }
        return true;
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        return true;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
//        HttpServletRequest req = (HttpServletRequest) request;
//        log.error("401 Unauthorized {}", req.getRequestURI());
//        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//        httpServletResponse.setStatus(httpServletResponse.SC_UNAUTHORIZED);
//        try {
//            response.setContentType("application/json;charset=UTF-8");
//            httpServletResponse.getWriter().println(new Gson().toJson(MyRestResult.failureDefault("您还没有登录")));
//        } catch (Exception e1) {
//        }
        return true;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response,
                                      Object mappedValue) {
        if (!super.isAccessAllowed(request, response, mappedValue)) {
            Subject subject = SecurityUtils.getSubject();
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            /*AuthenticationToken token = getUserRealToken(httpRequest);
            if(token != null) {
                subject.login(token);
            }*/
            /*if (subject.getPrincipal() == null) {
                AppInterceptor.appVerify(baseDao, log, httpRequest);
            }*/
            boolean isAllowed = super.isAccessAllowed(request, response, mappedValue);
            return isAllowed;
        }
        return true;
    }

    public static String COLLECTION_USER_LOGIN_AUTHZ = "user_login_authz";

    public String getUserByToken(String token) {
        String username = null;
//        try {
//            UserLoginAuthz authz = contextDao.userLoginAuthzMapper().getByToken(token);
//            if (authz != null) {
//                username = authz.getUsername();
//            }
//        } catch (Exception e) {
//            log.error("getUserByToken error", e);
//        }
        return username;
    }

    private AuthenticationToken getUserRealToken(HttpServletRequest httpRequest) {
        /*String username = httpRequest.getHeader("userName");
        String token = httpRequest.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }
        if (StringUtils.isBlank(username)) {
            username = httpRequest.getParameter("userName");
        }

        String phone = null;
        log.info("header username:{}, token{}", username, token);
        try {
            if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(token)) {
                phone = getUserByToken(token);
                if(StringUtils.isNotBlank(phone) && username.equals(MD5Utils.md5(phone))) {
                    return new UsernameToken(phone, null, System.currentTimeMillis());
                } else {
                    log.error("verify  failed, phone={}", phone);
                }
            }
        } catch (Exception e) {
            log.error("verify", e);
        }*/
        return null;
    }

    @Override
    protected boolean preHandle(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return super.preHandle(servletRequest, servletResponse);
    }

    public void doFilterInternal(ServletRequest var1, ServletResponse var2, FilterChain var3) throws ServletException, IOException {
        super.doFilterInternal(var1, var2, var3);
    }


}
